$(document).ready(function () {

    layui.use(function () {

        var layer = layui.layer;

        laydate = layui.laydate;
        table = layui.table;

        // 表格
        form = layui.form;
        form.on('select(needCharge)', function (data) {
            $('div[lay-filter="search"]').click();
        });
        form.on('select(searchType)', function (data) {
            $('div[lay-filter="search"]').click();
        });
        form.on('select(status)', function (data) {
            $('div[lay-filter="search"]').click();
        });

        form.on('submit(search)', function (data) {//监听查询提交
            params = data.field;
            params.pageSize = 10;
            queryTable()
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });


        form.on('submit(edit)', function (data) {//监听新增修改提交

            let msgType = "";
            if (curId) {
                msgType = "编辑"
                data.field.id = curId
            } else {
                msgType = "新增"
            }

            new AjaxChain()
                .setUrl('/material/save')
                .setMethod('post')
                .setData(JSON.stringify(data.field))
                .then(data => {
                    layer.close(drawer);
                    layer.msg(msgType + '成功', { icon: 1, time: 2000 });
                    queryTable()
                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();


            return false;
        });
        initSubMenu();
        queryTable();
        queryType()

    });
})
var params = {};//查询条件参数
var form, unit, laydate, table;
var drawer;//抽屉实例
var curId = null;//当前选中物资ID
var typeStr = '';//物资类型集合

// 查询物资类型
queryType = () => {

    new AjaxChain()
        .setUrl('/material/type/select')
        .then(data => {
            typeStr = data.reduce((x, y) => {
                return x + `<option value="${y.id}">${y.name}</option>`
            }, '<option value="">物资类型</option>')

            $('#search-type').empty().append(typeStr)

            form.render('select');
        })
        .send();
}
// 查询表格数据
queryTable = () => {
    let toolWidth = window.innerWidth / 1920 * 450
    layui.use('table', function () {

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/material/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: params
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                {
                    type: 'checkbox',
                    align: 'center',
                    width: 50,
                },
                { field: 'name', title: '物资名称', align: "center" }
                , { field: 'typeName', title: '类型', align: "center" }
                , { field: 'code', title: '编码', align: "center" }
                , { field: 'specification', title: '规格', align: "center" }
                , {
                    field: 'needChargeDesc', title: '需要充电', align: "center"
                }
                , { field: 'expiryDate', title: '有效期', align: "center" }
                , { field: 'statusDesc', title: '当前状态', align: "center" }
                , {
                    flex: 'right',
                    title: '操作',
                    align: 'center',
                    width: toolWidth,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool" style="justify-content: start;">
                                    <div onclick='tableHandle(4,"${d.code}")' class="table-record layui-btn">
                                    <img src="../static/img/icon1.png">详情
                                    </div>
                                    <div onclick='tableHandle(6,${res})' class="layui-btn">
                                    <img src="../static/img/icon4.png">二维码下载
                                    </div>
                                    <div onclick='opMaterials(1,"${d.id}")' class="table-edit layui-btn ${!(d.status == 1) ? 'layui-hide' : ''}">
                                    <img src="../static/img/menu/input.png">入库
                                    </div>
                                    <div onclick='opMaterials(2,"${d.id}")' class="table-edit layui-btn ${(d.status == 2 || d.status == 5) ? '' : 'layui-hide'}">
                                    <img src="../static/img/menu/output.png">出库
                                    </div>
                                    <div onclick='opMaterials(3,"${d.id}")' class="table-edit layui-btn ${(d.status == 2 || d.status == 5) ? '' : 'layui-hide'}">
                                    <img src="../static/img/menu/lend.png">出借
                                    </div>
                                    <div onclick='opMaterials(4,"${d.id}")' class="table-edit layui-btn ${(d.status == 4) ? '' : 'layui-hide'}">
                                    <img src="../static/img/menu/return.png">归还
                                    </div>
                                    <div onclick='tableHandle(1,${res})' class="table-edit layui-btn ${(d.status == 1) ? '' : 'layui-hide'}">
                                    <img src="../static/img/edit.png">编辑
                                    </div>
                                    <div onclick='tableHandle(2,${res})' class="table-del layui-btn ${(d.status == 1) ? '' : 'layui-hide'}">
                                    <img src="../static/img/del.png">删除
                                    </div>
                                </div>`;
                    },
                },
            ]]
            , height: '#contain-table-list-10'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip', 'limit'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页
                , limit: 20
                , limits: [20, 50, 100]

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

    });
}


// 列表功能按钮操作
tableHandle = (type, res) => {
    switch (type) {
        case 1://编辑
            curId = res.id
            openDrawer(2, res)
            break;
        case 2://删除

            layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

                new AjaxChain()
                    .setUrl('/material/delete')
                    .setData({ id: res.id })
                    .then(data => {
                        layer.msg('删除成功', { icon: 1, time: 1500 });
                        queryTable();
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();
            });
            break;

        case 3://新增 
            curId = null;
            openDrawer(1)
            break;
        case 4://详情

            queryMaterialsDetail(res)
            break;
        case 5://二维码批量下载
            generate()
            break;

        case 6://二维码单个下载
            generate(
                {
                    code: res.code,
                    name: res.name
                }
            )
            break;


        default:
            break;
    }
}



openDrawer = (type, res) => {
    drawer = layer.open({
        title: (type == 1 ? "新增" : "编辑") + '物资',
        type: 1,
        offset: 'r',
        anim: 'slideLeft', // 从右往左
        area: ['30%', '100%'],
        shade: 0.3,
        shadeClose: false,
        id: 'edit-offset',
        success: function (layero, index, that) {
            laydate.render({
                elem: '#expiryDate',
                trigger: 'click',
            });

            if (res) {
                form.val('editForm', res);

            } else {
                form.render(null, 'editForm');
            }


        },
        content: `<form class="layui-form layui-form-pane" id="add-form"  lay-filter="editForm"  action="">
                    <div class="form-item">
                        <label class="layui-form-label">物资名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="name" lay-affix="clear" placeholder="请输入" lay-verify="required"
                                class="layui-input">
                        </div>
                    </div>
                     <div class="form-item">
                        <label class="layui-form-label">物资编码</label>
                        <div class="layui-input-block">
                            <input type="text" name="code"  placeholder="请用读卡器读取卡片" lay-verify="required"
                                class="layui-input">
                        </div>
                    </div>
                   <div class="form-item">
                        <label class="layui-form-label">物资类型</label>
                        <div class="layui-input-block">
                            <select name="type" lay-filter="" lay-verify="required">
                                ${typeStr}
                            </select>
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">有效期</label>
                        <div class="layui-input-block">
                            <input type="text" name="expiryDate" lay-affix="clear" class="layui-input" id="expiryDate"  placeholder="请选择">
                        </div>
                    </div>
                    <div class="form-item pane-tool" >
                        <button type="reset" class="layui-btn layui-btn-primary btn-reset">重置</button>
                        <button class="layui-btn" lay-submit lay-filter="edit">确认</button>
                    </div>
                </form>`
    });

}

// 打开物资详情
function queryMaterialsDetail(code) {


    new AjaxChain()
        .setUrl('/material/detail/get')
        .setData({
            code: code
        })
        .then(data => {
            if (data == null) {
                layer.msg('未查询到该物资信息，请先添加')

            } else {
                layer.open({
                    title: data.name + '详情',
                    area: ['70%', '55%'],
                    // maxmin: true,
                    shade: 0.9,
                    move: false,
                    content: `<div class="contain-tab tab-con">
                                <div class="tab-title">基本信息</div>
                                <div class="tab-item">
                                    <div class="layui-col-md4">物资名称 ：${data.name}</div>
                                    <div class="layui-col-md4">物资类型 ：${data.typeName}</div>
                                    <div class="layui-col-md4">编码 ：${data.code}</div>
                                    <div class="layui-col-md4">当前状态 ：${data.statusDesc}</div>
                                    <div class="layui-col-md4">规格 ：${data.specification}</div>
                                    <div class="layui-col-md4">单位 ：${data.unit}</div>
                                    <div class="layui-col-md4">需要充电 ：${data.needChargeDesc}</div>
                                     <div class="layui-col-md4">上次充电时间 ：${data.lastChargeTime || '-'}</div>
                                    <div class="layui-col-md4">有效期 ：${data.expiryDate}</div>
                                </div>
                                <div class="tab-title">操作</div>
                                <div class="tab-item">
                                   <div onclick='opMaterials(1,"${data.id}")' class="table-edit layui-btn ${!(data.status == 1) ? 'layui-hide' : ''}">
                                    <img src="../static/img/menu/input.png">入库
                                    </div>
                                    <div onclick='opMaterials(2,"${data.id}")' class="table-edit layui-btn ${(data.status == 2 || data.status == 5) ? '' : 'layui-hide'}">
                                    <img src="../static/img/menu/output.png">出库
                                    </div>
                                    <div onclick='opMaterials(3,"${data.id}")' class="table-edit layui-btn ${(data.status == 2 || data.status == 5) ? '' : 'layui-hide'}">
                                    <img src="../static/img/menu/lend.png">出借
                                    </div>
                                    <div onclick='opMaterials(4,"${data.id}")' class="table-edit layui-btn ${(data.status == 4) ? '' : 'layui-hide'}">
                                    <img src="../static/img/menu/return.png">归还
                                    </div>
                                </div>
                            </div>`,
                    shadeClose: false,

                });
            }



        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();


}

// 物资操作
var curFile;
opMaterials = (type, materialId) => {

    curFile = null;
    curIndex = layer.open({
        type: 1,
        area: '40%',
        resize: false,
        shadeClose: false,
        title: '操作',
        content: `<form class="layui-form layui-form-pane" id="operate-form" lay-filter="operateForm" action="">
                    <div class="form-item">
                        <label class="layui-form-label">涉及人员</label>
                        <div class="layui-input-block">
                            <select name="operateUser" lay-search="{fuzzy: true}" lay-filter="audio-filter" lay-verify="required"></select>
                        </div>
                    </div>
                    <div class="form-item ${type!=3?"layui-hide":""}">
                        <label class="layui-form-label">物资去向</label>
                        <div class="layui-input-block"> 
                            <input type="text" name="lendDestination" placeholder="请输入"   class="layui-input">
                        </div>
                    </div>
                    <div class="form-item ${type!=4?"layui-hide":""}">
                        <label class="layui-form-label">归还来源</label>
                        <div class="layui-input-block"> 
                            <input type="text" name="backSource" placeholder="请输入"   class="layui-input">
                        </div>
                    </div>
                    <div class="form-item">
                        <label class="layui-form-label">操作时间</label>
                        <div class="layui-input-block">
                            <input type="text" name="operateTime" lay-affix="clear" id="operateTime-datetime"  placeholder="请选择"   class="layui-input">
                        </div>
                    </div>
                    <div class="form-item pane-tool">
                        <div class="layui-btn layui-edit-submit" lay-submit  lay-filter="operateHorn-save">确定</div>
                    </div>
                </form>`,

        success: function (index) {

            new AjaxChain()
                .setUrl('/person/select')
                .then(data => {

                    $('select[name="operateUser"]').empty().append(
                        data.reduce((x, y) => {
                            return x + `<option value="${y.id}">${y.name}</option>`
                        }, '<option value="">可搜索</option>')
                    )

                    form.render();

                })
                .catch(err => {
                    console.error('请求异常:', err);
                })
                .send();

            laydate.render({
                elem: '#operateTime-datetime',
                type: 'datetime',
                fullPanel: true
            });


            form.on('submit(operateHorn-save)', function (data) {//监听查询提交
                params = data.field
                params.operateType = type
                params.materialId = materialId

                new AjaxChain()
                    .setUrl('/material/operation/save')
                    .setMethod('post')
                    .setData(JSON.stringify(params))
                    .then(data => {
                        layer.close(curIndex);
                        layer.msg('操作成功', { icon: 1, time: 2000 });
                        queryTable()
                    })
                    .catch(err => {
                        console.error('请求异常:', err);
                    })
                    .send();


                return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
            });


        }
    });

}



// 生成二维码
function generate(result) {

    if (result) {

        var res = [result];
        var b64 = '';
    } else {

        var checkStatus = table.checkStatus('table');

        var res = checkStatus.data.map(({ code, name }) => ({ code, name }));
    }


    if (res.length === 0) {
        layer.msg('请在列表中至少选择一种物资');
    } else {


        var zip = new JSZip();
        var img = zip.folder("二维码");


        for (let i = 0; i < res.length; i++) {


            $('#qr-container').erweima({
                mode: 4,
                mSize: 20,
                text: window.location.protocol+'//'+window.location.host + '/fstation/html/h5.html?code=' + res[i].code,
                image: $("#qr-logo")[0],
            });
            var imgData = $('#qr-container>img').attr('src');


            var text = res[i].name + '(' + res[i].code + ')'
            var canvas = $('#qr-container>canvas')[0];
            var oldCtx = canvas.getContext('2d');

            var imgCanvas = document.createElement('canvas');
            imgCanvas.width = canvas.width;
            imgCanvas.height = canvas.height + 20;

            var ctx = imgCanvas.getContext('2d');
            ctx.fillStyle = 'white';
            ctx.fillRect(0, 0, imgCanvas.width, imgCanvas.height);
            ctx.putImageData(oldCtx.getImageData(0, 0, canvas.width, canvas.height), 0, 0);
            ctx.fillStyle = '#333';
            ctx.textBaseline = 'middle';
            ctx.textAlign = 'center';
            ctx.font = 'bolder 32px yahei';
            ctx.fillText(text, imgCanvas.width / 2, imgCanvas.height - 20);

            var imgData = imgCanvas.toDataURL('image/png');
            if (result) {
                b64 = imgData
            }
            img.file(new Date().getTime() + ".png", imgData.substring(imgData.indexOf(",") + 1), { base64: true });

        }

        if (result) {
            downloadBase64Image(b64, '物资二维码 ')

        } else {
            zip.generateAsync({
                type: "blob",  // 压缩类型
            }).then(function (content) {
                // see FileSaver.js
                saveAs(content, "二维码下载.zip");


            });
        }



    }

}

// 下载单张二维码
function downloadBase64Image(base64Data, filename) {
    // 将base64字符串转换为Blob对象
    const byteString = atob(base64Data.split(',')[1]);
    const mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
    const ab = new ArrayBuffer(byteString.length);
    const ia = new Uint8Array(ab);
    for (let i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([ab], { type: mimeString });

    // 创建一个指向Blob的URL
    const url = URL.createObjectURL(blob);

    // 创建一个a标签用于下载
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;

    // 模拟点击下载
    document.body.appendChild(link);
    link.click();

    // 清理：释放URL对象和移除a标签
    URL.revokeObjectURL(url);
    document.body.removeChild(link);
}

